import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { NzModalService } from 'ng-zorro-antd';
import { Router, ActivatedRoute } from '@angular/router';
import { CollectPlatformService } from 'src/app/service/collect-platform.service';
import { RequestService } from 'src/app/service/request.service';
import { Subject, Subscription } from 'rxjs';
import { ChangeDetectorRef } from "@angular/core";
import { debounceTime, throttleTime } from "rxjs/operators";
import { DragulaService } from 'ng2-dragula';
import { NzFormatEmitEvent, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { VOD_CATEGORY, VOD_CATEGORY_SAVE, VOD_PAGE, ossUri } from 'src/app/service/action_type';
declare var QRCode: any;
@Component({
  selector: 'app-collect-platform',
  templateUrl: './collect-platform.component.html',
  styleUrls: ['./collect-platform.component.less']
})
export class CollectPlatformComponent implements OnInit {

  constructor(private changeDetectorRef: ChangeDetectorRef, private requestService: RequestService, private collectPlatformService: CollectPlatformService, private dragulaService: DragulaService, private router: Router, private nzModalService: NzModalService, private activatedRoute: ActivatedRoute) { }
  @ViewChild('qrcodedom') qrcodedom: any;
  @ViewChild('treeCom1') treeCom1: any;
  @ViewChild('treeCom2') treeCom2: any;
  isLoad = false
  isOpenShare = false
  ossUrl: string = ossUri;
  collectPlatform = {
    id: "",
    userId: "",
    title: "",
    model: {
      carousel: [],
      items: []
    },
  }
  visible = null
  nodes = []
  nodes2 = []
  collectObj = {}
  selectCarouselNode = null
  selectColumnNode = null
  videoLib = []
  subs = new Subscription();
  public dataStream: Subject<null> = new Subject<null>();
  ngOnInit(): void {
    this.collectPlatformService.findAll().subscribe(res => {
      if (res["data"].length == 0) {
        this.collectPlatformService.create({
          title: '',
          model: '',
        }).subscribe((res2) => {
          this.collectPlatform = {
            ...res2['data'], model: !res2["data"].model ? {
              carousel: [],
              items: []
            } : JSON.parse(res2["data"].model)
          }
          this.getVideo()
        })
      } else {
        this.collectPlatform = {
          ...res['data'][0], model: !res["data"][0].model ? {
            carousel: [],
            items: []
          } : JSON.parse(res["data"][0].model)
        }
        this.getVideo()
      }
    })
    this.dataStream
      .pipe(debounceTime(500)).subscribe(() => {
        this.collectPlatformService.update(
          { ...this.collectPlatform, model: JSON.stringify(this.collectPlatform.model) }
          , +this.collectPlatform.id).subscribe(res => { })
      });
  }
  loadQRcode = false
  ngAfterViewInit() {
    setTimeout(() => {
      this.loadQRcode = true
      new QRCode(this.qrcodedom.nativeElement, {
        width: '148',
        height: '148'
      }).makeCode('https://player.ysjlive.com/collect-platform/' + this.collectPlatform.id);
    }, 1000)

  }
  getVideo() {
    this.requestService.get(VOD_CATEGORY).subscribe(async result => {
      let nodes = []
      let nodes2 = []
      for (let item of result['data']) {
        nodes.push({
          title: item.name,
          key: item.id
        })
        nodes2.push({
          title: item.name,
          key: item.id,
          isLeaf: true,
          date: item.date,
          id: item.id,
          showNum: 4,
          sort: 'date',
        })
        item.children = await this.findChildrenVideo(item.id)
      }
      this.videoLib = result["data"]

      this.nodes = nodes
      this.nodes2 = nodes2
      this.getCollectList()
      this.isLoad = true
    })
  }
  findChildrenVideo(id) {
    return new Promise(resolve => {
      this.requestService.post(VOD_PAGE, {
        "categoryId": id, "pagesize": 1000,
        "pageindex": 1,
      }).subscribe(result2 => {
        resolve(result2["data"].items)
      })
    })

  }
  nzEvent(event: NzFormatEmitEvent): void {
    const node = event.node;
    if (event.eventName == 'click') {
      if (node.level == 1 && node.isSelected) {
        this.selectCarouselNode = node
      }
    } else {
      if (event.eventName === 'expand') {
        if (node?.getChildren().length === 0 && node?.isExpanded) {
          this.loadNode(node.key).then(data => {
            node.addChildren(data);
          });
        }
      }
    }
  }
  nzEvent2(event: NzFormatEmitEvent): void {
    const node = event.node;
    if (event.eventName == 'click') {
      if (node.level == 0 && node.isSelected) {
        this.selectColumnNode = node
      }
    }
  }
  loadNode(key): Promise<NzTreeNodeOptions[]> {
    return new Promise(resolve => {
      this.requestService.post(VOD_PAGE, {
        "categoryId": key, "pagesize": 1000,
        "pageindex": 1,
      }).subscribe(result => {
        let res = []
        for (let item of result['data'].items) {
          res.push({
            title: item.title,
            playUrl: item.playUrl,
            save_supplier: item.save_supplier,
            logo: item.logo,
            watchCount: item.watchCount,
            date: item.date,
            key: item.id,
            isLeaf: true
          })
        }
        resolve(res)
      })
    });
  }
  selectColumnNodeDisabled() {
    let a = this.treeCom2.getSelectedNodeList()
    if (a.length == 0) {
      return true
    } else {
      return false
    }
  }
  selectCarouselNodeDisabled() {
    let a = this.treeCom1.getSelectedNodeList()
    if (a.length == 0) {
      return true
    } else {
      if (this.treeCom1.getSelectedNodeList()[0].level == 0) {
        return true
      } else {
        return false
      }
    }
  }
  selectCarousel() {
    this.collectPlatform.model.carousel.push({
      date: this.selectCarouselNode.origin.date,
      id: this.selectCarouselNode.origin.key,
      logo: this.selectCarouselNode.origin.logo,
      playUrl: this.selectCarouselNode.origin.playUrl,
      save_supplier: this.selectCarouselNode.origin.save_supplier,
      title: this.selectCarouselNode.origin.title,
      watchCount: this.selectCarouselNode.origin.watchCount,
    })
    this.selectCarouselNode = null
    this.visible = null
    this.save()
    this.getCollectList()
  }
  selectColumn() {
    this.collectPlatform.model.items.push({
      title: this.selectColumnNode.origin.title,
      date: this.selectColumnNode.origin.date,
      id: this.selectColumnNode.origin.id,
      showNum: 4,
      sort: 'date',
    })
    this.selectColumnNode = null
    this.visible = null
    this.save()
    this.getCollectList()
  }
  updateColumn(item, key) {
    if (typeof key == 'number') {
      item.showNum = key
    } else {
      item.sort = key
    }
    this.save()
    this.getCollectList()
  }
  removeCarousel(i) {
    this.collectPlatform.model.carousel.splice(i, 1)
    this.save()
    this.getCollectList()
  }
  removeCollect(i) {
    this.collectPlatform.model.items.splice(i, 1)
    this.save()
    this.getCollectList()
  }
  collectList = []
  getCollectList() {
    this.collectList = []
    for (let item of this.collectPlatform.model.items) {
      for (let item2 of this.videoLib) {
        if (item.id == item2.id) {
          let res = []
          res = JSON.parse(JSON.stringify(item2.children)).sort(function (a, b) {
            return b[item.sort == 'date' ? 'date' : 'watchCount'] - a[item.sort == 'date' ? 'date' : 'watchCount']
          });

          this.collectList.push(res.slice(0, item.showNum))
          this.changeDetectorRef.markForCheck();
          this.changeDetectorRef.detectChanges();
        }
      }
    }
  }
  @ViewChild('watchUrl2', { static: false }) watchUrl2: ElementRef;
  copy(inputId: string) {

    if (inputId === 'watchUrl2') {
      this.watchUrl2.nativeElement.select();
      document.execCommand('copy');
      this.nzModalService.success({
        nzTitle: '以复制到剪切板'
      });
    }

  }
  save() {
    this.dataStream.next();
  }
}
